package com.congee02.sw.var;

public class EqualSubstring {

    public int equalSubstring(String s, String t, int balance) {

        char[] x = s.toCharArray();
        char[] y = t.toCharArray();

        int n = s.length();

        // l = r = 0
        balance -= getCostAt(x, y, 0);
        int ans = balance < 0 ? 0 : 1;

        int l = 0;
        for (int r = 1 ; r < n ; r ++ ) {
            balance -= getCostAt(x, y, r);
            while (balance < 0) {
                balance += getCostAt(x, y, l ++);
            }
            ans = Math.max(ans, r - l + 1);
        }

        return ans;
    }

    private int getCostAt(char[] x, char[] y, int i) {
        return Math.abs(x[i] - y[i]);
    }

}
